package com.drinkian.business.comment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.drinkian.authentication.entity.po.User;
import com.drinkian.authentication.mapper.UserMapper;
import com.drinkian.business.comment.entity.po.Comment;
import com.drinkian.business.comment.mapper.CommentMapper;
import com.drinkian.business.comment.service.ICommentService;
import com.drinkian.entity.RequestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class CommentServiceImpl implements ICommentService {

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public RequestResult publish(Comment comment) {
        int insertResult = commentMapper.insert(comment);
        if (insertResult == 1) {
            return new RequestResult(HttpStatus.OK.value(), "添加评论成功！");
        } else {
            return new RequestResult(HttpStatus.OK.value(), "添加评论失败！");
        }
    }

    @Override
    public RequestResult updateCommentById(Comment comment) {
        Comment temp = commentMapper.selectById(comment.getId());
        if (Objects.isNull(temp)) {
            return new RequestResult(HttpStatus.BAD_REQUEST.value(), "未找到改评论！");
        }
        // 更新时间自动填入
        comment.setModifyTime(null);
        int updateResult = commentMapper.updateById(comment);
        if (updateResult == 1) {
            return new RequestResult(HttpStatus.OK.value(), "更新评论成功！");
        } else {
            return new RequestResult(HttpStatus.OK.value(), "更新评论失败！");
        }
    }

    @Override
    public RequestResult getCommentListByItemId(Long itemId) {
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        commentQueryWrapper.eq("item_id", itemId).orderByDesc("modify_time");
        List<Comment> commentList = commentMapper.selectList(commentQueryWrapper);
        for (Comment comment : commentList) {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("id", comment.getUploaderId());
            User user = userMapper.selectOne(userQueryWrapper);
            comment.setUser(user);
        }
        return new RequestResult(HttpStatus.OK.value(), commentList);
    }
}
